<?php
/*
	Version   :  1.14
	Created   :  20081004
	Modified  :  20090810
	Author    :  Pablo Ramirez
	co-Author :
	Descr     : Controlador "Orders"
	Changelog : 1.0 - Version Inicial
				1.1 - Se desarrolla logica para guardar inspecciones
				1.2 - Se modifica link para tabla de ordenes informadas
				1.4 - Se desarrolla logica para administracion de informes de contenedores
				1.5 - Se desarrolla logica para generacion de facturas
				1.6 - Se realizan modificaciones para el manejo de survey types y sus services asociados
				1.7 - Se guardaran dos registros en order_container y order_estimate, uno para box y otro para mach
				1.8 - Se utiliza el est_codigo de acuerdo a la busqueda para no duplicar order_estimates  
				1.9 - Se modifica el ingreso de contenedores al schedule_order_container para que inserte dependiento del tipo
				1.10 - En Survey Detail se crea reefer_inspection_flag para que se haga timbre solo si se requiere inspeccion de machine
				1.11 - Se redirecciona a APP_DIR . en deleteInformFile, se maneja error cuando archivo no existe
				1.12 - Se agrega flag has_reefer para detectar checkbox de ingreso de timbre en orden sin contenedores
				1.13 - Se mejora el metodo de view para las ordenes y sus detalles
				1.14 - Se obtiene valor sut_musthave usando consulta a base de datos por order_id en survey_detail()
*/
class OrdersController extends AppController
{
	var $name                     = 'Orders';
	var $uses                     = array('Order','Owner','Container','SurveyType','ServiceType','Surveyor','Depot','OrderContainer', 'OrderDepot', 'OrderEstimate', 'ContainerSchedule', 'DepotSchedule', 'ContainerType', 'Country');
	var $components               = array('Upload');
	var $helpers                  = array('Html','Javascript','Ajax','jsCalendar');
	var $estado_ingresada         = 'A';
	var $estado_ingresada_com     = 'Orden Ingresada';
	var $estado_programada        = 'P';
	var $estado_programada_com    = 'Orden Programada';
	var $estado_inspeccionada     = 'I';
	var $estado_inspeccionada_com = 'Orden Inspeccionada';
	var $estado_informada         = 'N';
	var $estado_informada_com     = 'Orden Informada';
	var $estado_revisada          = 'R';
	var $estado_revisada_com      = 'Orden Revisada';
	var $estado_enviada           = 'S';
	var $estado_enviada_com       = 'Orden Enviada';
	var $order                    = null;
	
	function index() {
	
		$this->layout = 'main';
		
		if (empty($this->data)) {
			$this->set('orders', $this->Order->findAll("ord_estado = '$this->estado_ingresada'","*","ord_codigo ASC"));
		}
	}
	
	
	function getOrdersByStatus($order_status = null) {
		
		$this->layout = 'ajax';
		
		switch($order_status){
			case $this->estado_ingresada:
				$this->set('orders', $this->Order->findAll("ord_estado = '$this->estado_ingresada'","*","ord_codigo ASC"));
				$this->render('admitted');
				break;
			case $this->estado_programada:
				$this->set('orders', $this->Order->findAll("ord_estado = '$this->estado_programada'","*","ord_codigo ASC"));
				$this->render('programmed');
				break;
			case $this->estado_inspeccionada:
				$this->set('orders', $this->Order->findAll("ord_estado = '$this->estado_inspeccionada'","*","ord_codigo ASC"));
				$this->render('inspected');
				break;
			case $this->estado_informada:
				$this->set('orders', $this->Order->findAll("ord_estado = '$this->estado_informada'","*","ord_codigo ASC"));
				$this->render('informed');
				break;
			default:
				$this->set('orders', $this->Order->findAll("ord_estado = '$this->estado_ingresada'","*","ord_codigo ASC"));
				$this->render('index');
				break;
		}
	}
	
	
	function add($stage = null, $order_id = null) {
		
		$this->layout = 'main';
		
		if (empty($stage)) {
			$owners = $this->Owner->generateList();
			
			
			if (!empty($owners)) {
				$owners = array('A'=>'Seleccionar Propietario')+$owners;
			}
			
			if (!empty($this->data)){
				
				//Logica para asignacion de estados
				$this->data['Order']['ord_estado'] = $this->estado_ingresada;
				$this->data['Order']['ord_comentarioestado'] = $this->estado_ingresada_com;
				
				//Logica para asignar la autocompletacion
				//$this->data['Order']['owc_codigo'] = $this->data['Container']['cod_codigo'];
				//unset($this->data['Container']);
				
				$this->set('owners', $owners);
				$this->set('surveyTypes', $this->SurveyType->generateList());
				$this->set('countries', $countries = $this->Country->generateList());
				
				if ($this->Order->save($this->data)){
					//$this->Session->setFlash('Orden Ingresada');
					$this->redirect('orders/add/depots/'.$this->Order->id);
				}
			} else {
				//$image_id = $this->Order->getLastInsertId(); 
				$this->set('lastId', $this->Order->getLastInsertId()); 
				
				$this->set('surveyTypes', $this->SurveyType->generateList());
				$this->set('serviceTypes', $this->ServiceType->generateList());
				$this->set('owners', $owners);
				$this->set('countries', $countries = $this->Country->generateList());
				
				//$this->set('orders', $this->Order->findAll()); <-- para probar el HBTM
			}
		} elseif ($stage == 'depots') {
			$this->Order->id = $order_id;
			$this->order = $order_id;
			
			$this->data = $this->Order->read();
			$ord_country = $this->data['Order']['cou_codigo'];

			if (!empty($this->data['OrderDepot'])){
				$d = "";
				$q = array();
				$i = 0;
				foreach ( $this->data['OrderDepot'] as $ord_dep) {
					$d .= '"';
					$d .= $ord_dep['dep_codigo'];
					$d .= '"';
					$d .= ",";
				}
				$cod_depots = substr($d,0,strlen($d)-1);
				
				$depots = $this->Depot->generateList("dep_country = '$ord_country' and dep_codigo not in ($cod_depots)");
				
				if ($this->data['SurveyType']['sut_musthave'] == 'T') {
					$this->set('qty_containers', $this->OrderContainer->findCount("ord_codigo = $order_id and dep_codigo in ($cod_depots)"));
					
					$order_containers = $this->OrderContainer->findAll("ord_codigo = $order_id and dep_codigo in ($cod_depots)", "dep_codigo");
					
					foreach ($order_containers as $container) {
						$depot = $container['OrderContainer']['dep_codigo'];
						@ $q[$depot] = $q[$depot] + 1;
					}
					
					$this->set('depot_containers',$q);
				} elseif ($this->data['SurveyType']['sut_musthave'] == 'F') {
					
					$order_depots = $this->OrderDepot->findAll("ord_codigo = $order_id and dep_codigo in ($cod_depots)", "dep_codigo, ode_cantcontenedores");
					
					foreach ($order_depots as $depot) {
						$ode_cantcontenedores = $depot['OrderDepot']['ode_cantcontenedores'];
						$depot = $depot['OrderDepot']['dep_codigo'];
						
						@ $q[$depot] = $ode_cantcontenedores;
						//$q = array('0','1');
					}
					
					$this->set('depot_containers', $q);
					//$this->set('depot_containers', $this->OrderDepot->find("ord_codigo = '$order_id' and dep_codigo = '$dep_codigo'","ode_cantcontenedores"));
				}
				
			} else {
				$depots = $this->Depot->generateList("dep_country = '$ord_country'");
			}
			
			if (!empty($depots)) {
					$depots = array(0=>'Seleccionar Deposito')+$depots;
			}
			
			$this->set('depots', $depots);
			$this->set('ord_codigo', $order_id);
			$this->set('ord_sut_musthave', $this->data['SurveyType']['sut_musthave']);
			$this->set('ord_sut_codigo', $this->data['Order']['sut_codigo']);
			$this->set('order_depots', $this->data['OrderDepot']);
		}
	}
	
	
	function getOwnerInfo() {
		$this->layout = 'ajax';
		$own_codigo = $this->data['Order']['own_codigo'];
		$this->set('owner_details', $this->Owner->find("own_codigo = '$own_codigo'", null, null, -1));
		//$this->set('aaa', $this->data);
	}
	
	function testObserve($a, $b, $c) {
		$this->layout = 'ajax';		
		///surveyDetail/' . $ord_codigo . '/' . $order_container['dep_codigo'] . '/' . $order_container['cod_codigo']
		$this->set('a', $a);
		$this->set('b', $b);
		$this->set('c', $c);

		$this->set('output', 'SALIDA');
	}
	/*function depots($order_id) {
		$this->Order->id = $order_id;
		$this->data = $this->Order->read();
	}*/
	
	
	function depositos() {
		$this->layout = 'ajax';
		
		if(empty($this->data)) {
			$depots = $this->Depot->generateList();
			
			if (!empty($depots)) {
					$depots = array(0=>'Seleccionar Deposito')+$depots;
			}
			
			//$orders = $this->Order->findAll();
			$this->set('orders', $this->Order->findAll());
			$this->set('depots', $depots);
			
		} else {
			if (empty($this->data['OrderDepot']['ode_cantcontenedores'])) {
				$this->data['OrderDepot']['ode_cantcontenedores'] = 0;
			}
			if ($this->OrderDepot->save($this->data['OrderDepot'])) {
				$this->redirect('orders/add/depots/'.$this->data['OrderDepot']['ord_codigo']);
			} else {
				$this->redirect('error');
			}
		}
	}
	
	
	function getDepotInfo($order_id) {
		$this->layout = 'ajax';
		$this->Order->id = $order_id;
		$sut_codigo = $this->Order->read("Order.sut_codigo, SurveyType.sut_musthave");
		$dep_codigo = $this->data['Depot']['dep_codigo'];
		
		if ($sut_codigo['SurveyType']['sut_musthave'] == 'T') {
			//$this->set('depot_details', $this->Depot->find("dep_codigo = '$dep_codigo'", null, null, -1));
			$this->set('dep_qty_containers', $this->OrderDepot->findCount("ord_codigo = '$order_id' and dep_codigo = '$dep_codigo'"));
		} elseif ($sut_codigo['SurveyType']['sut_musthave'] == 'F') {
			$this->set('dep_qty_containers', $this->OrderDepot->find("ord_codigo = '$order_id' and dep_codigo = '$dep_codigo'","ode_cantcontenedores"));
		}
		
		$this->set('ord_detail', $sut_codigo);
		$this->set('ord_codigo', $order_id);
		$this->set('dep_codigo', $dep_codigo);
		
	}
	
	
	function containers($depot_id = null, $order_id = null) {
		/* 
			Guarda informacion en order_containers y schedule_order_containers
			Desde el ajax form de la vista containers.thtml incluida en la 
			vista de ingreso de contanedores en order/add/depots
		*/
		$this->layout = 'ajax';
		
		if (!empty($this->data)){
				//print_r($this->data);
				/*unset ($this->data);
				$this->data['OrderContainer']['ord_codigo'] = 29;
				$this->data['OrderContainer']['cod_codigo'] = 'CLHU404543';
				//$this->data['Container']['cod_codigo'] = 'CLHU404543';*/
				
				$ord_codigo = $this->data['OrderDepot']['ord_codigo'];
				$dep_codigo = $this->data['OrderDepot']['dep_codigo'];
				$cod_codigo = $this->data['OrderContainer']['cod_codigo'];
				$cot_codigo = $this->data['OrderContainer']['cot_codigo'];
				
			if ($this->OrderContainer->save($this->data['OrderContainer'])){
				//insertar registros para programacion de box/machine
				//$schedule_box['id'] = "";
				
				//obtiene informacion acerca del tipo de contenedor para determinar si guarda box/mach en schedule_order_containers
				$cot_reefer_flag = $this->ContainerType->field("cot_reefer_flag","cot_codigo = '$cot_codigo'");
				
				$schedule_box['ord_codigo'] = $ord_codigo;
				$schedule_box['dep_codigo'] = $dep_codigo;
				$schedule_box['cod_codigo'] = $cod_codigo;
				$schedule_box['set_codigo'] = "--";
				$schedule_box['ocs_tipo'] = "1";
				
				if ($this->ContainerSchedule->save($schedule_box)){
					$ERROR = 0;
					$ERROR_DESC = "OK";
				} else {
					$ERROR = 2;
					$ERROR_DESC = "No se pudo guardar registro #1 en container schedule";
					$this->redirect('error');
				}
				
				//guarda registro de machine solo si el container type lo indica
				if ($cot_reefer_flag == 'T') { 
					$schedule_mach['id'] = "";
					$schedule_mach['ord_codigo'] = $ord_codigo;
					$schedule_mach['dep_codigo'] = $dep_codigo;
					$schedule_mach['cod_codigo'] = $cod_codigo;
					$schedule_mach['set_codigo'] = "--";
					$schedule_mach['ocs_tipo']   = "2";
					
					if ($this->ContainerSchedule->save($schedule_mach)){
						$ERROR = 0;
						$ERROR_DESC = "OK";
					} else {
						$ERROR = 2;
						$ERROR_DESC = "No se pudo guardar registro #2 en container schedule";
						$this->redirect('error');
					}
				}
				// guardar relacion order_depot solamente si no existe
				$exist_order_depot = $this->OrderDepot->find("ord_codigo = '$ord_codigo' and dep_codigo = '$dep_codigo'");
				if (empty($exist_order_depot)) {
					if (empty($this->data['OrderDepot']['ode_cantcontenedores'])) {
						$this->data['OrderDepot']['ode_cantcontenedores'] = 0;
					}
					if ($this->OrderDepot->save($this->data['OrderDepot'])) {
						//$this->redirect('/orders/add/depots/'.$this->data['OrderContainer']['ord_codigo']);
					}
				}
				
				//$this->redirect('/orders/add/depots/'.$this->data['OrderContainer']['ord_codigo']);
				
			} else {
				$this->redirect('error');
			}
			$this->Order->id = $this->data['OrderDepot']['ord_codigo'];
			$order_details = $this->Order->read();
			
			/*
			//LOOK -- tengo que encontrar los containers POR DEPOSITO por cada orden
			$order_depot = $this->OrderContainer->findAll("ord_codigo = '$order_id' and dep_codigo = '$depot_id'");
			if (!empty($order_depot)) {
				foreach ($order_depot as $odc) {
					$temp = array();
					foreach($odc['OrderContainer'] as $key=>$value) {
						$temp[$key] = $value;
					}
					$odcArray[] = $temp;
				}
				$this->set('containers', $odcArray);
			} else {
				$this->set('containers', array());
			}
			$this->set('depot', $this->Depot->find("dep_codigo = '$depot_id'", array('dep_nombre'))); // se setea esta variable para usar en el formulario de agregar contenedores a deposito
			$this->set('container_types', $this->ContainerType->generateList());
			
			$this->set('depot_id', $this->data['OrderDepot']['dep_codigo']);*/
			
			$order_id = $this->data['OrderDepot']['ord_codigo'];
			$dep_codigo = $this->data['OrderContainer']['dep_codigo'];
			
			$order_depot = $this->OrderContainer->findAll("ord_codigo = '$order_id' and dep_codigo = '$dep_codigo'");
			if (!empty($order_depot)) {
				foreach ($order_depot as $odc) {
					$temp = array();
					foreach($odc['OrderContainer'] as $key=>$value) {
						$temp[$key] = $value;
					}
					$odcArray[] = $temp;
				}
				$this->set('containers', $odcArray);
			} else {
				$this->set('containers', array());
			}
			
			$this->set('order', $order_details);
			
			$this->render('order_container_list','ajax');
			
		} else {
			$this->Order->id = $order_id;
			
			$order_details = $this->Order->read();
			
			//LOOK -- tengo que encontrar los containers POR DEPOSITO por cada orden
			$order_depot = $this->OrderContainer->findAll("ord_codigo = '$order_id' and dep_codigo = '$depot_id'");
			if (!empty($order_depot)) {
				foreach ($order_depot as $odc) {
					$temp = array();
					foreach($odc['OrderContainer'] as $key=>$value) {
						$temp[$key] = $value;
					}
					$odcArray[] = $temp;
				}
				$this->set('containers', $odcArray);
			} else {
				$this->set('containers', array());
			}
			
			//ciclo para obtener el dep_nombre a partir de depot_id
			/*foreach ($order_details['OrderDepot'] as $od) {
				if ($od['ord_codigo'] == $depot_id) {
					$this->set('dep_nombre', $od['dep_codigo']);
					break;
				}
			} -- obsoleto porque se necesita antes de guardar registro en Order*/
			
			$this->set('depot', $this->Depot->find("dep_codigo = '$depot_id'", array('dep_nombre'))); // se setea esta variable para usar en el formulario de agregar contenedores a deposito
			
			$this->set('order', $order_details);
			
			//$this->set('containers', $order_details['Container']);
			//$this->set('containers', $this->OrderContainer->findAll("ord_codigo = '$order_id' and dep_codigo = '$depot_id'"));
			
			$this->set('depot_id', $depot_id);
			
			$this->set('container_types', $this->ContainerType->generateList());
			//$this->data['OrderContainer']['cod_codigo'] = 'CLHU404543';
		}
	}
	
	
	function schedule($order_id = null) {
	
		$this->layout = 'main';
		$fecha=date('Ymd');
		$File = "../tmp/logs/schedule-$fecha.txt";
		$Handle = fopen($File, 'a');
		//$Data = "$ani;$linea;$hora_ini;$hora_fin;$apli\n";
		fwrite($Handle, "iniciando schedule\n");
		
		
		if ((empty($this->data)) and (isset($order_id))) {
			
			// Presentar Formulario
			fwrite($Handle, "Presentando formulario\n");
			$this->Order->id = $order_id;
			$order_details = $this->Order->read();
			$order_survey_type = $order_details['Order']['sut_codigo'];
			//$srv_type_prefix = $this->ServiceType->generateList("sut_codigo = '--'");
			//$srv_type = $this->ServiceType->generateList("sut_codigo = '$order_survey_type'");
			//$service_types = $srv_type_prefix + $srv_type;
			
			$default_set_codigo = array('--' => 'Select a Service Type');
			$availables_set_codigo = $this->ServiceType->generateList("sut_codigo = '$order_survey_type'");
			
			$service_types = @array_merge($default_set_codigo,$availables_set_codigo);
			
			//Se comenta debido a problema para calendarizar ordenes con sut_musthave en T
			//unset($order_details['OrderContainer']);
			
			if (!empty($service_types)) {
				$this->set('service_types', $service_types);
			} else {
				$this->set('service_types', array('--' => 'Select a Service Type'));
			}
			
			//$order_containers = $this->OrderContainer->findAll("ord_codigo = $order_id");
			if ($order_details['SurveyType']['sut_musthave'] == 'T') {
				$i = 0;
				foreach ($order_details['OrderContainer'] as $order_container_detail) {
					fwrite($Handle, "iterando por order_containers para orden " . $order_id . "\n");
					$ord_codigo = $order_id;
					$dep_codigo = $order_container_detail['dep_codigo'];
					$cod_codigo = $order_container_detail['cod_codigo'];
					$cot_codigo = $order_container_detail['cot_codigo'];
					$cot_reefer_flag = $this->ContainerType->field("cot_reefer_flag", "cot_codigo = '$cot_codigo'");
					
					$order_container_schedule = $this->ContainerSchedule->findAll( "ord_codigo = '$order_id' and 
																					cod_codigo = '$cod_codigo'",
																					"id,
																					 ord_codigo,
																					 dep_codigo,
																					 cod_codigo,
																					 ocs_tipo,
																					 set_codigo,
																					 soc_surveydate",
																					"id");
					
					foreach ($order_container_schedule as $container_schedule) {
						$schedule_containers['OrderContainer'][$i]['id']              = $container_schedule['ContainerSchedule']['id'];
						$schedule_containers['OrderContainer'][$i]['ord_codigo']      = $order_id;
						$schedule_containers['OrderContainer'][$i]['dep_codigo']      = $dep_codigo;
						$schedule_containers['OrderContainer'][$i]['cod_codigo']      = $cod_codigo;
						$schedule_containers['OrderContainer'][$i]['ocs_tipo']        = $container_schedule['ContainerSchedule']['ocs_tipo'];
						$schedule_containers['OrderContainer'][$i]['cot_codigo']      = $cot_codigo;
						$schedule_containers['OrderContainer'][$i]['cot_reefer_flag'] = $cot_reefer_flag;
						$schedule_containers['OrderContainer'][$i]['set_codigo']      = $container_schedule['ContainerSchedule']['set_codigo'];
						$schedule_containers['OrderContainer'][$i]['soc_surveydate']  = $container_schedule['ContainerSchedule']['soc_surveydate'];
						
						fwrite($Handle, "id              : ". $schedule_containers['OrderContainer'][$i]['id']."\n");
						fwrite($Handle, "ord_codigo      : ". $schedule_containers['OrderContainer'][$i]['ord_codigo']."\n");
						fwrite($Handle, "dep_codigo      : ". $schedule_containers['OrderContainer'][$i]['dep_codigo']."\n");
						fwrite($Handle, "cod_codigo      : ". $schedule_containers['OrderContainer'][$i]['cod_codigo']."\n");
						fwrite($Handle, "ocs_tipo        : ". $schedule_containers['OrderContainer'][$i]['ocs_tipo']."\n");
						fwrite($Handle, "cot_codigo      : ". $schedule_containers['OrderContainer'][$i]['cot_codigo']."\n");
						fwrite($Handle, "cot_reefer_flag : ". $schedule_containers['OrderContainer'][$i]['cot_reefer_flag']."\n");
						fwrite($Handle, "set_codigo      : ". $schedule_containers['OrderContainer'][$i]['set_codigo']."\n");
						fwrite($Handle, "soc_surveydate  : ". $schedule_containers['OrderContainer'][$i]['soc_surveydate']."\n");
						
						$i++;
					}
					//$i++;
				}
				
				$order_details['OrderContainer'] = $schedule_containers['OrderContainer'];
				
			} elseif ($order_details['SurveyType']['sut_musthave'] == 'F'){
				$i = 0;
				foreach ($order_details['OrderDepot'] as $order_depot_detail) {
					$dep_codigo = $order_depot_detail['dep_codigo'];
					$depot_schedule = $this->DepotSchedule->find("ord_codigo = '$order_id' and dep_codigo = '$dep_codigo'");
					$order_details['OrderDepot'][$i]['id'] = $depot_schedule['DepotSchedule']['id'];
					$order_details['OrderDepot'][$i]['sod_surveydateinit'] = $depot_schedule['DepotSchedule']['sod_surveydateinit'];
					$i++;
				}
			}

			$this->OrderSchedule->id = $order_id;
			

			if ($order_details['SurveyType']['sut_musthave'] == 'T') {
				//Validar datos para inspeccion Off-Hire
				$qty_containers = $this->OrderContainer->findCount("ord_codigo = $order_id");
				if ($qty_containers < 1) {
					$this->Session->setFlash('Debe incluir al menos un contenedor para la inspeccion de tipo ' . $order_details['Order']['sut_codigo']);
					$this->redirect('orders/add/depots/'.$order_id);
				}	
			} elseif ($order_details['SurveyType']['sut_musthave'] == 'F') {
			
				//Validar datos para inspeccion On-Hire
				$order_depots = $this->OrderDepot->findAll("ord_codigo = $order_id");
				$qty_containers = 0;
				foreach ($order_depots as $order_depot) {
					$qty_containers = $qty_containers + $order_depot['OrderDepot']['ode_cantcontenedores'];
				}
				//se agrega condicion que no se cumple, ahora para las inspecciones sin contenedores, 0 significa que no se sabe el numero de contenedores
				if ($qty_containers < 0) { 
					$this->Session->setFlash('Debe indicar la cantidad de contenedores para la inspeccion de tipo ' . $order_details['Order']['sut_codigo']);
					$this->redirect('orders/add/depots/'.$order_id);
				}
			}
			
			//$this->set('order_details', $order_details);
			$this->set('order_details', $order_details);
			//pr($order_details);
			//break;
			
		} elseif (!empty($this->data)) {
			
			// Guardar datos enviados desde schedule.thtml
			//pr($this->data);
			//break;
			fwrite($Handle, "Recibido datos desde formulario\n");
			$ERROR = 0;
			$i = 0;
			
			$cod_codigo_resumen = array();
			
			if ($this->data['Order']['sut_musthave']  == 'T') {
				fwrite($Handle, "musthave en True\n");
				fwrite($Handle, "iniciando rutina por cada item\n");
				
				//$cod_anterior = "";
				//$fcount = 0;
				foreach ($this->data as $item) {
					//El bloque siguiente es solo para los subarrays [OrderSchedule_N]
					if (isset($item['cod_codigo'])) {
						unset ($buffer);
						$box = "";
						$mach = "";
						//$ocs_tipo = $item['ocs_tipo'];
						$cod_codigo = $item['cod_codigo'];
						if ($item['ocs_tipo'] == '1') {
							$ocs_tipo = 'box';
						} else if ($item['ocs_tipo'] == '2') {
							$ocs_tipo = 'mach';
						} else {
							$ERROR = 1;
							$ERROR_DESC = "No se pudo determinar ocs_tipo";
							$this->Session->setFlash($ERROR_DESC);
							$this->redirect('orders/schedule/'.$item['ord_codigo']);
						}
						fwrite($Handle, "box: ".$item['box']."| mach: ".$item['mach']."| ocs_tipo: ".$item['ocs_tipo']." = ".$ocs_tipo."\n");
						
						if (($item['box'] == 'on') or ($item['mach'] == 'on')) {
							fwrite($Handle, "box o mach on\n");
							$buffer['ContainerSchedule']['set_codigo'] = $item['set_codigo'];
							$buffer['ContainerSchedule']['soc_surveydate'] = $item['soc_surveydate'];
							if (isset($cod_codigo_resumen[$cod_codigo])) {
								$cod_codigo_resumen[$cod_codigo]++;
							} else {
								$cod_codigo_resumen[$cod_codigo] = 1;
							}
						} else {
							fwrite($Handle, "box o mach off\n");
							$buffer['ContainerSchedule']['set_codigo'] = '--';
							$buffer['ContainerSchedule']['soc_surveydate'] = "";
							if (!isset($cod_codigo_resumen[$cod_codigo])) {
								$cod_codigo_resumen[$cod_codigo] = 0;
							}
						}
						fwrite($Handle, "res: ".$cod_codigo_resumen[$cod_codigo]."\n");
						
						$buffer['ContainerSchedule']['ord_codigo'] = $item['ord_codigo'];
						$buffer['ContainerSchedule']['ord_codigo'] = $item['ord_codigo'];
						$buffer['ContainerSchedule']['cod_codigo'] = $item['cod_codigo'];
						$buffer['ContainerSchedule']['dep_codigo'] = $item['dep_codigo'];
						$buffer['ContainerSchedule']['ocs_tipo']   = $item['ocs_tipo'];
						
						//$chk = ($box + $mach);
						fwrite($Handle, "ord_codigo: ".$buffer['ContainerSchedule']['ord_codigo']." | cod_codigo: ". $buffer['ContainerSchedule']['cod_codigo'] ." | dep_codigo: ".$buffer['ContainerSchedule']['dep_codigo']." | ocs_tipo: ".$ocs_tipo." | set_codigo: ".$buffer['ContainerSchedule']['set_codigo']." | soc_surveydate: ".$buffer['ContainerSchedule']['soc_surveydate']."\n");
						//fwrite($Handle, "chk: ". $chk ."\n");
						if ($ERROR == 0) {
							//ESTO ES PARA QUE HAGA UPDATE Y NO INSERTE NUEVO REGISTRO
							$this->ContainerSchedule->id = $item['id'];
							if (!$this->ContainerSchedule->save($buffer['ContainerSchedule'])) {
								$ERROR = 2;
								$ERROR_DESC = "No es posible guardar el detalle de la programacion";
								fwrite($Handle, "ERROR: ".$ERROR_DESC."\n");
								$this->Session->setFlash($ERROR_DESC);
								$this->redirect('orders/schedule/'.$item['ord_codigo']);
							}
						}
					}
				}
			} elseif ($this->data['Order']['sut_musthave']  == 'F') {
				foreach ($this->data as $depot_schedule) {
					if (isset($depot_schedule['dep_codigo'])) {
						/*echo $i.'<br />';
						print_r($container_schedule);
						echo '<br />';
						echo '<br />';*/
						$this->DepotSchedule->id = $depot_schedule['id'];
						$buffer['DepotSchedule']['ord_codigo'] = $depot_schedule['ord_codigo'];
						$buffer['DepotSchedule']['dep_codigo'] = $depot_schedule['dep_codigo'];
						$buffer['DepotSchedule']['sod_surveydateinit'] = $depot_schedule['sod_surveydateinit'];
						
						if ($this->DepotSchedule->save($buffer['DepotSchedule'])){
							$ERROR = 0;
						} else {
							//ERROR: no se pudo guardar la actualizacion de la orden
							$this->redirect('error');
						}
						/*print_r($buffer['ContainerSchedule']);
						echo '<br />';*/
					}
					$i++;
				}
			}
			//$this->data->Order->id = $order_id;
									/*								$ERROR_DESC = 'Alguno de los contenedores no fue programado';
								$this->Session->setFlash($ERROR_DESC);
								$this->redirect('orders/schedule/2');
								*/
			//pr($cod_codigo_resumen);
			//break;
			if (array_search('0',$cod_codigo_resumen)) {
				$ERROR = 3;
				$ERROR_DESC = "Alguno de los contenedores no fue programado";
				fwrite($Handle, "ERROR: ".$ERROR_DESC."\n");
				$this->Session->setFlash($ERROR_DESC);
				$this->redirect('orders/schedule/'.$item['ord_codigo']);
			}
			
			if ($ERROR == 0) {
				$this->data['Order']['ord_estado'] = $this->estado_programada;
				$this->data['Order']['ord_comentarioestado'] = $this->estado_programada_com;
				if ($this->Order->save($this->data['Order'])) {
					$this->redirect('orders');
				} else {
					//ERROR: no se pudo guardar la informacion de programacion de la orden
					$this->Session->setFlash("Algun error inesperado ha ocurrido");
					$this->redirect('orders/schedule/'.$item['ord_codigo']);
				}
			} else {
				fwrite($Handle, "ERROR: Algun error a ocurrido -".$ERROR."\n");
				$this->redirect('orders/schedule/'.$item['ord_codigo']);
			}

		} else {
			//ERROR: para presentar el formulario de programacion debe venir order_id
			$this->redirect('error');
		}
		fclose($Handle);
	}
	
	
	function orderConsolidate($order_id) {
		$this->Order->id = $order_id;
		$this->data['Order']['ord_estado'] = $this->estado_programada;
		$this->data['Order']['ord_comentarioestado'] = $this->estado_programada_com;
		if ($this->Order->save($this->data)){
			//$this->Session->setFlash('Orden Programada');
			$this->redirect('orders');
		}
	
	}
	
	
	function delOrderContainer($container_id, $order_id) {
		$this->layout = 'ajax';
		if (!empty($container_id)) {
			$this->OrderContainer->del($container_id);
			$soc_ids = $this->ContainerSchedule->findAll("ord_codigo = '$order_id' and cod_codigo = '$container_id'");
			foreach ($soc_ids as $soc_id) {
				$schedule_id = $soc_id['ContainerSchedule']['id'];
				$this->ContainerSchedule->del($schedule_id);
			}
		}
		
		$this->Order->id = $order_id;
		$order_details = $this->Order->read();
		
		$this->set('order', $order_details['Order']);
		$this->set('containers', $order_details['OrderContainer']);
		$this->render('cot_list','ajax');
	}
	
	
	function delOrderDepot($depot_id, $order_id) {

		$this->layout = 'main';

		if (!empty($depot_id)) {
			$this->OrderDepot->execute("DELETE from order_containers WHERE ord_codigo = '$order_id' and dep_codigo = '$depot_id'");
			$this->OrderDepot->execute("DELETE from order_depots     WHERE ord_codigo = '$order_id' and dep_codigo = '$depot_id'");
		}
		
		$this->redirect('orders/add/depots/'.$order_id,'ajax');
	}
	
	
	function edit($order_id = null) {
		
		$this->layout = 'main';

		$owners = $this->Owner->generateList();
		if (!empty($owners)) {
			$owners = array('A'=>'Seleccionar Propietario')+$owners;
		}

		if (!empty($this->data)){
			//Logica para asignacion de estados.. aca se comenta para que no cambie el estado
			//$this->data['Order']['ord_estado'] = $this->estado_ingresada;
			$this->data['Order']['ord_comentarioestado'] = $this->estado_ingresada_com;

			//Logica para asignar la autocompletacion
			//$this->data['Order']['owc_codigo'] = $this->data['Container']['cod_codigo'];
			//unset($this->data['Container']);

			$this->set('owners', $owners);
			$this->set('surveyTypes', $this->SurveyType->generateList());

			if ($this->Order->save($this->data)){
				//$this->Session->setFlash('Orden Ingresada');
				$this->redirect('orders/view/'.$this->Order->id);
			}
		} else {
			$this->Order->id = $order_id;
			$this->data = $this->Order->read();
			$this->set('lastId', $this->Order->getLastInsertId()); 
			$this->set('surveyTypes', $this->SurveyType->generateList());
			$this->set('owners', $owners);
			$this->set('countries', $countries = $this->Country->generateList());

			//$this->set('orders', $this->Order->findAll()); <-- para probar el HBTM
		}
						
		/*		####
		$this->Order->id = $order_id;
		
		if (empty($this->data)){
			$this->data = $this->Order->read();
		}else{
			if ($this->Order->save($this->data)){
				$this->flash('Item Editado','/orders');
			} else {
				$this->Session->setFlash('Error al editar el Item');
			}
		}*/
		
	}
	
	
	function view($order_id) {
	
		$this->layout = 'main';
		if ((empty($this->data)) and (isset($order_id))) {
			// Presentar Detalles de la Orden
			$this->Order->id = $order_id;
			//$this->OrderSchedule->id = $order_id;
			
			$order_details = $this->Order->read();
			$order_depots = $order_details['OrderDepot'];
			$order_containers = $order_details['OrderContainer'];
			$order_depots = $order_details['OrderDepot'];
			$cou_codigo = $order_details['Order']['cou_codigo'];
			$order_details['Order']['cou_nombre'] = $this->Country->field('cou_nombre',"cou_codigo = '$cou_codigo'");
			$result = array();
			//pr($order_details);
			//pr($order_containers);
			//break;
			
			foreach ($order_containers as $order_container) {
				
				$cod_codigo = $order_container['cod_codigo'];
				if (strlen($order_container['cod_codigo']) < 12) {
					//se trabaja con el cod_contenedor primario (sin -MACH)
					$oco_informe_box = $order_container['oco_informe'];
					$oco_informe_mach = $this->OrderContainer->field('oco_informe',"ord_codigo = '$order_id' and cod_codigo = '$cod_codigo-MACH' and oco_tipo = 2");
					if ((strlen($oco_informe_box) > 5) and file_exists(WWW_ROOT . 'files/' . $oco_informe_box)) {
						$oco_informe_box = 'getContainerDocument/'. $order_id .'/'. $order_container['cod_codigo'];
					} else {
						$oco_informe_box = '';
					}
					if ((strlen($oco_informe_mach) > 4) and file_exists(WWW_ROOT . 'files/' . $oco_informe_mach)) {
						$oco_informe_mach = 'getContainerDocument/'. $order_id .'/'. $order_container['cod_codigo'] .'-MACH';
					} else {
						$oco_informe_mach = '';
					}
					
					/*if ($order_details['ord_estado'] == 'P') {
						$soc_survey_date = 
					} else {
						$soc_survey_date = ;
					}*/
					
					array_push($result, array('dep_codigo'=>$order_container['dep_codigo'],
										'cod_codigo'=>$order_container['cod_codigo'],
										'soc_survey_date'=> $this->ContainerSchedule->field('soc_surveydate',"ord_codigo = '$order_id' and cod_codigo = '$cod_codigo' and ocs_tipo = 1"),
										'stamp'=>'surveyDetail/'.$order_id.'/'.$order_container['dep_codigo'].'/'.$order_container['cod_codigo'].'/Stamp',
										'oco_informe_box'=> $oco_informe_box,
										//'oco_informe_mach'=>$this->OrderContainer->field('oco_informe',"ord_codigo = '$order_id' and cod_codigo = '$cod_codigo-MACH' and oco_tipo = 2")));
										'oco_informe_mach'=> $oco_informe_mach));
				}
				
			}
			
			if (empty($result)) {
				foreach ($order_depots as $order_depot) {
				$dep_codigo = $order_depot['dep_codigo'];
				array_push($result, array('dep_codigo'=> $dep_codigo,
										'cod_codigo'=>'',
										'soc_survey_date'=> $this->DepotSchedule->field('sod_surveydateinit',"ord_codigo = '$order_id' and dep_codigo = '$dep_codigo'"),
										'stamp'=>'',
										'oco_informe_box'=> '',
										'oco_informe_mach'=> ''));
				}
			}

			//pr($result);
			$this->set('survey_details', $result);
			$this->set('order_details', $order_details);
		} elseif (!empty($this->data)) {
			// Guardar datos enviador desde schedule.thtml
			//print_r($this->data);
			// Setear el nuevo estado de la order
			$this->data['Order']['ord_estado'] = $this->estado_programada;
			$this->data['Order']['ord_comentarioestado'] = $this->estado_programada_com;
			if ($this->OrderSchedule->save($this->data['OrderSchedule'])){
				if ($this->Order->save($this->data['Order'])){
					$this->redirect('orders');
				} else {
					//ERROR: no se pudo guardar la actualizacion de la orden
					$this->redirect('error');
				}
			} else {
				//ERROR: no se pudo guardar la informacion de programacion de la orden
				$this->redirect('error');
			}
		} else {
			//ERROR: para presentar el formulario de programacion debe venir order_id
			$this->redirect('error');
		}
		
	}
	
	
	function survey($order_id = null) {
	
		$this->layout = 'survey_form';
		
		if ((empty($this->data)) and (isset($order_id))) {
			// Presentar Detalles de la Orden
			$this->Order->id = $order_id;
			//$this->OrderSchedule->id = $order_id;
		
			$this->set('order_details', $this->Order->read());
		} elseif (!empty($this->data)) {
			$order_id = $this->data['Order']['ord_codigo'];
			$this->Order->id = $order_id;
			//Validar que se insertaron todos los Containers
			//Obtener los containers de la orden
			$order_details = $this->Order->read();
			
			$order_containers = $order_details['OrderContainer'];
			
			
			$ERROR = '';
			$ERROR_DESC = '';
			//Por cada uno checkear si existe informacion detallada en Container
			foreach ($order_containers as $order_container) {
				$cod_codigo = $order_container['cod_codigo'];
				
				if($order_container['oco_tipo'] == 1) { // 1.7
					$container_detail = $this->Container->find("cod_codigo = '$cod_codigo'");
					if (!empty($container_detail['Container'])) {
						$ERROR = '0';
						$ERROR_DESC = "";
					} else {
						$ERROR = '1';
						$ERROR_DESC = $cod_codigo;
						break;
					}
				}
			}
			
			//Buscar si es necesario ir a informar, basta que uno necesite fotos para que sea deba informarse
			$order_estimates = $this->OrderEstimate->findAll("ord_codigo = '$order_id'", "est_photos");
			foreach($order_estimates as $order_estimate) {
				if($order_estimate['OrderEstimate']['est_photos'] != 0) {
					$FLAG_INFORM = 'T';
					break;
				} else {
					$FLAG_INFORM = 'F';
				}
			}
				
			// Setear el nuevo estado de la order
			if ($FLAG_INFORM == 'T') {
				$this->data['Order']['ord_estado'] = $this->estado_inspeccionada;
				$this->data['Order']['ord_comentarioestado'] = $this->estado_inspeccionada_com;
			} elseif ($FLAG_INFORM == 'F') {
				$this->data['Order']['ord_estado'] = $this->estado_informada;
				$this->data['Order']['ord_comentarioestado'] = $this->estado_informada_com;
				$this->data['Order']['ord_fechacierre'] = date("Y-m-d");
			} else {
				$ERROR == '2';
				$ERROR_DESC = 'Error inesperado al obtener datos de estimate';
			}
			
			if ($ERROR == '0') {
				if ($this->Order->save($this->data['Order'])) {
					$ERROR = '0';
					$this->redirect('orders');
				} else {
					//ERROR: no se pudo guardar la informacion de programacion de la orden
					$ERROR = '9';
					$ERROR_DESC = 'Error general al intentar guardar datos';
					$this->Session->setFlash($ERROR_DESC);
					$this->redirect('orders/survey/' . $this->data['Order']['ord_codigo']);
				}
			} else {
				//ERROR: Se encontro informacion de contenedores incompleta
				$this->Session->setFlash('No se ha insertado completamente el detalle en el contenedor ' . $ERROR_DESC);
				$this->redirect('orders/survey/' . $this->data['Order']['ord_codigo']);
			}
		} else {
			//ERROR: para presentar el formulario de programacion debe venir order_id
			$this->Session->setFlash('Esta orden no tiene detalles para consolidar ' . $ERROR_DESC);
			$this->redirect('orders/survey/' . $this->data['Order']['ord_codigo']);
			//$this->redirect('error');
		}
		
	}


	function surveyDetail($order_id, $depot_id, $container_id = null, $mach = null) {
				
		//este valor viene seteado desde on_survey_detail por el observe field		
		if (strlen($this->data['OrderContainer']['cod_codigo']) > 4){
			$container_id = $this->data['OrderContainer']['cod_codigo'];
			unset($this->data);
		}
		
		$this->Container->id = $container_id;

		if ($mach == 'Stamp'){
			$render_file = 'survey_stamp';
			$this->layout = 'survey_form';
		} else {
			$render_file = 'survey_detail';
			$this->layout = 'ajax';
		}
		
		$order_sut_codigo = $this->Order->field('sut_codigo',"ord_codigo = '$order_id'");
		$order_sut_musthave = $this->SurveyType->field('sut_musthave',"sut_codigo = '$order_sut_codigo'");
		$cot_codigo = $this->OrderContainer->field('cot_codigo', "ord_codigo = '$order_id' and cod_codigo = '$container_id'");
		$this->set('ord_codigo', $order_id);
		$this->set('cod_codigo', $container_id);
		$this->set('cot_codigo', $cot_codigo);
		$this->set('codigo_state_area', $depot_id);
		//1.10 Inicio Cambios
		//$this->set('cot_reefer_flag', $this->ContainerType->field('cot_reefer_flag', "cot_codigo = '$cot_codigo'")); //Ya no se usa mas cot_reefer_flag
		$soc_info = $this->ContainerSchedule->findAll("ord_codigo = '$order_id' and
														   dep_codigo = '$depot_id' and
														   cod_codigo = '$container_id'", //conditions
														   array('ocs_tipo','set_codigo'), //fields
														   'ocs_tipo ASC', //order
														   '2' //limit
														   ); 

		
		
		if(count($soc_info) > 1) {
			$ocs_tipo_1_set_codigo = $soc_info[0]['ContainerSchedule']['set_codigo'];
			$ocs_tipo_2_set_codigo = $soc_info[1]['ContainerSchedule']['set_codigo'];
		} else {
			$ocs_tipo_1_set_codigo = '--';
			$ocs_tipo_2_set_codigo = '--';
		}
		
		if (strlen($ocs_tipo_1_set_codigo) > 3 and  $ocs_tipo_2_set_codigo != '--') {
			$this->set('reefer_inspection_flag', 'T'); 
		} else {
			$this->set('reefer_inspection_flag', 'F'); // Se instancia como inspeccion sin reefer
		}
		//1.10 Fin Cambios
		
		$this->set('dep_codigo', $depot_id);
		$this->set('surveyors', $this->Surveyor->generateList());
		
		if ($container_id!=NULL) {
			//Si la orden tiene codigos de contenedor
			$this->set('sut_musthave',$order_sut_musthave);
			
			$this->data = $this->Container->read();
			if ($mach == 'Mach') {
				//Mach viene solamente del observeField ajax desde survey_detail.thtml
				$container_id = $container_id . '-MACH';
				$this->set('oes_tipo','2');
			} else {
				$container_id = $container_id;
				$this->set('oes_tipo','1');
			}
			$order_estimate = $this->OrderEstimate->find("ord_codigo = '$order_id' and cod_codigo = '$container_id'");
			if (is_array($order_estimate)) {
				$this->data = array_merge($this->data, $order_estimate);
			} else {
				$this->data = array('Container'     => array('cot_codigo'   => $cot_codigo,
															 'con_mgw'   => '0',
															 'con_tare'  => '0',
															 'con_manuf' => '0',
															 'con_onhdate' => date("Y-m-d")),
									'OrderEstimate' => array('est_original' => '0',
															 'est_final'    => '0',
															 'est_saving'   => '0',
															 'est_id'  => '0',
															 'est_cl'  => '0',
															 'est_wt'  => '0',
															 'est_ir'  => '0',
															 'est_pti' => '0',
															 'est_line'   => '0',
															 'est_client' => '0',
															 'est_thirds' => '0',
															 'est_class'  => '0'));
				
			}
			$this->render($render_file);
		} elseif(strlen($this->data['OrderContainer']['cod_codigo']) > 4 ) {
			$this->set('sut_musthave', $order_sut_musthave);	
			$this->Container->id = $this->data['OrderContainer']['cod_codigo'];
			$this->data = $this->Container->read();
			$this->set('cot_codigo', $this->data['Container']['cot_codigo']);
			$container_id = $this->data['Container']['cod_codigo'];
			$this->set('cod_codigo', $container_id);
			$this->set('codigo_state_area', $container_id);
			$order_estimate = $this->OrderEstimate->find("ord_codigo = '$order_id' and cod_codigo = '$container_id'");
			if (is_array($order_estimate)) {
				//$this->data += $order_estimate;
				$this->data = @array_merge($this->data, $order_estimate);
			} 
			$this->render($render_file);
		} elseif($this->data['OrderContainer']['cod_codigo'] == 'A') {
			$this->render('blank');
		} elseif($this->data['OrderContainer']['cod_codigo'] == 'B') {
				$this->set('sut_musthave', $order_sut_musthave);
				$this->set('container_types', $this->ContainerType->generateList());
				$this->set('service_types',$this->ServiceType->generateList("sut_codigo = '$order_sut_codigo'"));
				$this->data = array('Container'     => array('cot_codigo'   => '0',
															 'con_mgw'   => '0',
															 'con_tare'  => '0',
															 'con_manuf' => '0',
															 'con_onhdate' => date("Y-m-d")),
									'OrderEstimate' => array('est_original' => '0',
															 'est_final'    => '0',
															 'est_saving'   => '0',
															 'est_id'  => '0',
															 'est_cl'  => '0',
															 'est_wt'  => '0',
															 'est_ir'  => '0',
															 'est_pti' => '0',
															 'est_line'   => '0',
															 'est_client' => '0',
															 'est_thirds' => '0',
															 'est_class'  => '0'));
				//$this->render('survey_detail');
				$this->render($render_file);
				
		} else {
			$this->set('sut_musthave', $order_sut_musthave);
			$order_containers = $this->OrderContainer->generateList("ord_codigo = '$order_id'");
			if(!is_array($order_containers)) { 
				$order_containers = array(); 
			}
			$order_containers = array('B'=>'Add Container')+$order_containers;
			$order_containers = array('A'=>'Select Container')+$order_containers;
			$this->set('order_containers', $order_containers);
			$this->set('jjj', $this->data);
			
			$this->render('on_survey_detail');
		}
		/*pr($this->data);
		break;*/
		//$this->set('container_detail', $this->Container->find("cod_codigo = '$container_id'"));
	}

	function orderContainerList($order_id, $dep_codigo) {
		$this->layout = 'ajax';
		$order_containers = $this->OrderContainer->generateList("ord_codigo = '$order_id'");
		if(!is_array($order_containers)) { 
			$order_containers = array(); 
		}
		$order_containers = array('B'=>'Add Container')+$order_containers;
		$order_containers = array('A'=>'Select Container')+$order_containers;
		$this->set('ord_codigo', $order_id);
		$this->set('dep_codigo', $dep_codigo);
		$this->set('order_containers', $order_containers);
		$this->render('on_survey_detail');
	}
	
	function saveSurveyDetail() {
		$this->layout = 'ajax';
		$ERROR = '0';
		$container = $this->params['data']['Container'];
		$order_estimate = $this->data['OrderEstimate'];
		
		//pr($container);
		//pr($order_estimate);
		//break;
		
		$ord_codigo = $order_estimate['ord_codigo'];
		$cod_codigo = $container['cod_codigo'];
		$dep_codigo = $order_estimate['dep_codigo'];
		
		if ($order_estimate['is_reefer'] > 0 ) { // 1.12
			$order_estimate['oes_tipo'] = 2;	
		}
		
		if ($order_estimate['oes_tipo'] > 1 ) { // 1.7
			//if ($this->OrderEstimate->)
			//$this->data['OrderEstimate']['est_codigo'] = null;
			$container['cod_codigo'] .= '-MACH';
			$cod_codigo_final = $container['cod_codigo'];
			$this->data['OrderEstimate']['est_codigo'] = $this->OrderEstimate->field('est_codigo', "ord_codigo = '$ord_codigo' and cod_codigo = '$cod_codigo_final'"); //1.8
		}
		
		$this->Container->begin(); 
		$this->OrderEstimate->begin();
		
		
		if ($this->Container->save($this->params['data']['Container'])) {
			$ERROR = '0';
			$ERROR_DESC = 'OK';
			$this->data['OrderEstimate']['cod_codigo'] = $container['cod_codigo'];
			$this->data['OrderEstimate']['oes_tipo'] = $order_estimate['oes_tipo']; //1.12 --  se agrega esto porque al guardar un -MACH deja oes_tipo = 1
			
			if ($this->OrderEstimate->save($this->data['OrderEstimate'])) {
				$ERROR = '0';
				$ERROR_DESC = 'OK';
				$cod_set_tipo = $order_estimate['oes_tipo'];
				$this->OrderContainer->begin();
				$this->data['OrderContainer']['ord_codigo'] = $order_estimate['ord_codigo'];
				$this->data['OrderContainer']['dep_codigo'] = $order_estimate['dep_codigo'];
				$this->data['OrderContainer']['cod_codigo'] = $container['cod_codigo'];
				$this->data['OrderContainer']['cot_codigo'] = $container['cot_codigo'];
				$this->data['OrderContainer']['oco_tipo']   = $cod_set_tipo; // 1.10 - Se agrega campo ocs_tipo para obtener set_codigo
				
				//pr($this->data['OrderContainer']);
				//break;
				if (!isset($this->data['OrderContainer']['set_codigo'])) {
					$this->data['OrderContainer']['set_codigo'] = $this->ContainerSchedule->field("set_codigo",
																								  "ord_codigo = '$ord_codigo' and 
																								   cod_codigo ='$cod_codigo' and 
																								   dep_codigo = '$dep_codigo' and
																								   ocs_tipo   = '$cod_set_tipo'"); //1.8
				}
				if ($this->OrderContainer->save($this->data['OrderContainer'])) {
					$ERROR = '0';
					$ERROR_DESC = 'OK';
				} else {
					$ERROR = '1';
					$ERROR_DESC = 'Problemas para almacenar la informacion de Order Container';
				}
			} else {
				$ERROR = '2';
				$ERROR_DESC = 'Problemas para almacenar la informacion de Order Estimate';
			}
		} else {
			$ERROR = '3';
			$ERROR_DESC = 'Problemas para almacenar la informacion del contenedor';
		}
		
		if ($ERROR == '0') {
			$this->OrderContainer->commit(); 
			$this->Container->commit(); 
			$this->OrderEstimate->commit(); 
			$this->set('location', 'grabe bien!');
			$this->set('datos', $this->params['data']);
			$this->set('symbol', 'green_yes.jpeg');
		} else {
			$this->OrderContainer->rollback(); 
			$this->Container->rollback(); 
			$this->OrderEstimate->rollback(); 
			$this->set('location', 'intente grabar pero no pude');
			$this->set('datos', $this->params['data']['Container']);
			$this->set('symbol', 'red_no.png');
		}
		
		//si se esta guardando una inspeccion sin contenedores se actualiza el timbre por uno nuevo (desde guardar y continuar)
		if ($this->data['SurveyType']['sut_musthave'] == 'F') {
			$ord_codigo = $order_estimate['ord_codigo'];
			$this->set('dep_codigo', $order_estimate['dep_codigo']);
			$this->set('ord_codigo', $ord_codigo);
			$this->set('cod_codigo', $container['cod_codigo']);
			$this->set('cot_codigo', $container['cot_codigo']);
			$this->set('codigo_state_area', $order_estimate['dep_codigo']);
			$this->set('sut_musthave','F');
			$this->set('reefer_inspection_flag', $container['reefer_inspection_flag']);
			$this->set('container_types', $this->ContainerType->generateList());
			$this->set('surveyors', $this->Surveyor->generateList());
			$order_sut_codigo = $this->Order->field('sut_codigo',"ord_codigo = '$ord_codigo'");
			$this->set('service_types',$this->ServiceType->generateList("sut_codigo = '$order_sut_codigo'"));
			$this->data = array('Container'     => array('cot_codigo'   => '0',
														 'con_mgw'   => '0',
														 'con_tare'  => '0',
														 'con_manuf' => '0'),
								'OrderEstimate' => array('est_original' => '0',
														 'est_final'    => '0',
														 'est_saving'   => '0',
														 'est_id'  => '0',
														 'est_cl'  => '0',
														 'est_wt'  => '0',
														 'est_ir'  => '0',
														 'est_pti' => '0',
														 'est_line'   => '0',
														 'est_client' => '0',
														 'est_thirds' => '0',
														 'est_class'  => '0'));
														 
			$this->render('survey_detail','ajax');
		}
		
	}


	function testing() {
		echo 'THIS DATA';
		echo '<br />';
		pr($this->data);
		echo '<br />';
		echo 'THIS PARAMS';
		echo '<br />';
		pr($this->params);
		echo '<br />';
		 //pr($this->params['form']['File']);
		echo '<br />';
		break;
	}
	
	
	function inform($order_id = null) {
		
		$this->layout = 'main';
		
		if (!empty($this->data['Order'])) {
			//si se esta intentando consolidar datos para pasar la orden a informada
			$order_id = $this->data['Order']['ord_codigo'];
			$this->Order->id = $order_id;
			$order_details = $this->Order->read();
		} elseif (isset($order_id)) {
			//si se esta ingresando a informar contenedores
			$this->Order->id = $order_id;
			$order_details = $this->Order->read();
		} else {
			$this->redirect('error');
		}
		//---$this->set('order_details', $this->Order->read());
		
		$order_containers = array();
		
		foreach ($order_details['OrderContainer'] as $order_container) {
			$ord_codigo = $order_container['ord_codigo'];
			$cod_codigo = $order_container['cod_codigo'];
			$oeArray = array();
			
			$oes = $this->OrderEstimate->find("ord_codigo = $ord_codigo and cod_codigo = '$cod_codigo'", "est_photos");
			if ($oes['OrderEstimate']['est_photos'] == 1) {
				foreach($oes as $oe) {
					$temp = array();
					//foreach($oe['OrderEstimate'] as $key=>$value) {
					foreach($oe as $key=>$value) {
						$temp[$key] = $value;
					}
					$oeArray[] = $temp;
				}
				
				array_push($order_containers, array('Order' => $order_details['Order'],
													'Container' => $order_container, 
													'Estimates' => $oeArray['0']));
													//'Estimates' => $this->OrderEstimate->findAll("ord_codigo = $ord_codigo")));
			}
		}
			
		if ((empty($this->data)) and (isset($order_id))) {
			// Presentar Detalles de la Orden
			$this->set('order_details', $order_containers);
			
		} elseif (!empty($this->data['Order'])) {
			
// 			pr($this->data);
// 			break;
			//Validar que se insertaron todos los Containers
			//Obtener los containers de la orden
			//$order_id = $this->data['Order']['ord_codigo'];
			//$this->Order->id = $order_id;
			//$order_details = $this->Order->read();
			//$order_containers = $order_details['OrderContainer'];
			
			//$order_containers = $this->OrderEstimate->findAll("", "est_photos");
			
			//Por cada uno checkear si existe informacion detallada en Container
			foreach ($order_containers as $order_container) {
				$cod_codigo = $order_container['Container']['cod_codigo'];
				$container_detail = $this->OrderContainer->find("ord_codigo = '$order_id' and cod_codigo = '$cod_codigo'");
				if (isset($container_detail['OrderContainer']['oco_informe'])) {
					$ERROR = '0';
					$ERROR_DESC = "";
				} else {
					$ERROR = '1';
					$ERROR_DESC = "El contenedor " . $cod_codigo . " requiere de informe";
					break;
				}
			}
			
			if ($ERROR == '0') {
				$this->data['Order']['ord_fechacierre'] = date("Y-m-d");
				$this->data['Order']['ord_estado'] = $this->estado_informada;
				$this->data['Order']['ord_comentarioestado'] = $this->estado_informada_com;
				if ($this->Order->save($this->data['Order'])) {
					//$this->Session->setFlash('El informe fue subido correctamente');
					$this->redirect('/orders/');
				} else {
					$this->Session->setFlash('Hubo un error al actualizar el estado de la orden');
					$this->redirect('/orders/inform/' . $this->data['Order']['ord_codigo']);
				}
			} else {
				$this->Session->setFlash($ERROR_DESC);
				$this->redirect('/orders/inform/' . $this->data['Order']['ord_codigo']);
			}
		
		} else {
			//ERROR: para presentar el formulario de programacion debe venir order_id
			$this->redirect('error');
		}
		
	}
	
	
	function informDetail($order_id, $container_id) {
		$this->layout = 'ajax';
		
		$order_container =  $this->OrderContainer->find("ord_codigo = '$order_id' and cod_codigo = '$container_id'", "dep_codigo,cot_codigo,oco_tieneestimate,oco_informe"); 
		
		$this->Container->id = $container_id;
		$this->set('ord_codigo', $order_id);
		$this->set('cod_codigo', $container_id);
		$this->set('dep_codigo', $order_container['OrderContainer']['dep_codigo']);
		$this->set('cot_codigo',  $order_container['OrderContainer']['cot_codigo']);
		$this->set('oco_tieneestimate',  $order_container['OrderContainer']['oco_tieneestimate']);
		$this->set('oco_informe',  $order_container['OrderContainer']['oco_informe']);
		$this->set('surveyors', $this->Surveyor->generateList());
		$this->data = $this->Container->read();
		
		//$this->set('container_detail', $this->Container->find("cod_codigo = '$container_id'"));
		//$this->Container->
		//$this->set();
	}
	
	
	function saveInformDetail() {
		$ERROR = '0';
		$this->Order->id = $this->data['Order']['ord_codigo'];
		$destination = WWW_ROOT . 'files/';
		//$this->Session->setFlash('data attach no esta vacio');
		//$this->redirect('orders/inform/' . $this->data['Order']['ord_codigo']);

		if (!empty($this->params['form']['File']['name'])) {
			$file = $this->params['form']['File'];
			if (!file_exists($destination . $file['name'])) {
				$upload = $this->Upload->upload($file, $destination, $file['name']);
				if (!$upload) {
					$this->data['OrderContainer']['oco_informe'] = $file['name'];
					// CAMBIAR ACA... SE DEBE ACTUALIZAR order_containers con el dato oco_informe
					if ($this->OrderContainer->save($this->data['OrderContainer'])) {
						$ERROR = '0';
					} else {
						$ERROR = '1';
						$ERROR_DESC = 'Hubo un problema al subir el informe';
					}
				} else {
					$ERROR = '2';
					$ERROR_DESC = $upload;
				}
			} else {
				$ERROR = '3';
				$ERROR_DESC = 'El archivo que esta intentando subir ya existe';
			}
			
			if ($ERROR == '0') {
				//$this->data['Order']['ord_estado'] = $this->estado_informada;
				//if ($this->Order->save($this->data['Order'])) {
					$this->Session->setFlash('El informe fue subido correctamente');
					$this->redirect(APP_PATH . '/orders/inform/' . $this->data['Order']['ord_codigo']);
				//} else {
				//	$this->Session->setFlash('Hubo un error al actualizar el estado de la orden');
				//	$this->redirect('/orders/inform/' . $this->data['Order']['ord_codigo']);
				//}
			} else {
				$this->Session->setFlash($ERROR_DESC);
				$this->redirect(APP_PATH . '/orders/inform/' . $this->data['Order']['ord_codigo']);
			}
		} else {
			$this->Session->setFlash('Debe seleccionar el archivo');
			$this->redirect(APP_PATH . '/orders/inform/' . $this->data['Order']['ord_codigo']);
		}
	}
	
	
	function deleteInformFile($order_id, $container_id) {
		$ERROR = '0';
		$ERROR_DESC = 'OK';
		$order_container =  $this->OrderContainer->find("ord_codigo = '$order_id' and cod_codigo = '$container_id'"); 
		$destination = WWW_ROOT . 'files/';
		$file = $order_container['OrderContainer']['oco_informe'];
		$order_container['OrderContainer']['oco_informe'] = NULL;
		
		if (file_exists($destination . $file)) {
			if (unlink($destination . $file)) {
				$ERROR = '0';
				$ERROR_DESC = 'Archivo Eliminado Correctamente';
			} else {
				$ERROR = '1';
				$ERROR_DESC = 'No fue posible eliminar el archivo de informe';
			}
		} else {
			$ERROR = '0';  //se deja como error cero, para que de todas maneras se modifique campo en order_container
			$ERROR_DESC = 'Archivo No Existe, se elimina asociacion con este contenedor!';
		}
		
		if ($ERROR == '0') {
			if ($this->OrderContainer->save($order_container)) {
				$this->Session->setFlash($ERROR_DESC);
				$this->redirect(APP_PATH . '/orders/inform/' . $order_id);   //1.11
			} else {
				$this->Session->setFlash($ERROR_DESC);
				$this->redirect(APP_PATH . '/orders/inform/' . $order_id);   //1.11
			}
		} else {
			$this->Session->setFlash($ERROR_DESC);
			$this->redirect(APP_PATH . '/orders/inform/' . $order_id);       //1.11
		}
	
	}
	
	function getContainerDocument($order_id, $container_id) {
		$ERROR = '0';
		$ERROR_DESC = 'OK';
		$oco_informe = $this->OrderContainer->field("oco_informe", "ord_codigo = '$order_id' and cod_codigo = '$container_id'");
		/*pr($oco_informe);
		break;*/
		if (file_exists(WWW_ROOT . 'files/' . $oco_informe)) {
			$this->redirect('files/'.$oco_informe);
		} else {
			$ERROR = '1';
			$ERROR_DESC = 'File not found!';
			$this->Session->setFlash($ERROR_DESC);
			$this->redirect('orders/view/' . $order_id);
		}
	}
}
?>